package cn.wnhyang.solon.filter;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.exception.SameTokenInvalidException;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.exception.StatusException;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.noear.solon.core.handle.Result;
import org.noear.solon.validation.ValidatorException;

import static org.smartboot.http.common.enums.HttpStatus.*;

/**
 * @author wnhyang
 * @date 2025/4/28
 **/
@Slf4j
@Component(index = -99)
public class GlobalFilter implements Filter {
    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        try {
            chain.doFilter(ctx);
        } catch (ValidatorException e) {
            log.error("ValidatorException异常", e);
            ctx.status(e.getCode());
            ctx.render(Result.failure(e.getCode(), e.getMessage()));
        } catch (StatusException e) {
            log.error("StatusException异常", e);
            ctx.status(e.getCode());
            ctx.render(Result.failure(e.getCode(), e.getMessage()));
        } catch (NotPermissionException | NotRoleException e) {
            log.error("异常", e);
            ctx.status(FORBIDDEN.value());
            ctx.render(Result.failure(FORBIDDEN.value(), FORBIDDEN.getReasonPhrase()));
        } catch (NotLoginException | SameTokenInvalidException e) {
            log.error("异常", e);
            ctx.status(UNAUTHORIZED.value());
            ctx.render(Result.failure(UNAUTHORIZED.value(), UNAUTHORIZED.getReasonPhrase()));
        } catch (Throwable e) {
            log.error("服务异常", e);
            ctx.status(INTERNAL_SERVER_ERROR.value());
            ctx.render(INTERNAL_SERVER_ERROR);
        } finally {
            // 必须清理上下文
        }
    }
}
